package com.freen.fadmin.controller.jwt.SysuserApi.sysuser;

import com.freen.fadmin.controller.jwt.JwtSysuserBaseController;
import com.freen.fadmin.entity.sysuser.SysRole;
import com.freen.fadmin.entity.sysuser.SysUser;
import com.freen.fadmin.repository.sysuser.SysPermissionRepository;
import com.freen.fadmin.repository.sysuser.SysRoleRepository;
import com.freen.fadmin.repository.sysuser.SysUserRepository;
import com.freen.fadmin.util.result.ExceptionMsg;
import com.freen.fadmin.util.result.Response;
import com.freen.fadmin.util.result.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/SysApi/sysUser")
public class SysUserController extends JwtSysuserBaseController {
    @Autowired
    HttpServletRequest request;
    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private SysRoleRepository sysRoleRepository;
    @Autowired
    private SysPermissionRepository sysPermissionRepository;

    // 用户 SysUser
    //restful控制器编写
    //index
    @ResponseBody
    @RequestMapping(value = "",method = RequestMethod.GET)
    public Response APIindex(@RequestParam(value = "page", defaultValue = "0") Integer start,
                             @RequestParam(value = "limit", defaultValue = "5") Integer limit,
                             @RequestParam(value = "keyword",required = false) String  keyword,
                             @RequestParam(value = "sort", defaultValue = "id") String  sortq){
        start = start < 0 ? 0 : start;
        Sort sort = Sort.by(Sort.Direction.DESC, sortq);
        Pageable pageable = PageRequest.of(start-1,limit,sort);
        //得到了初始的数据
        Page<SysUser> page;
        //判断是否有 keyword 如果有就找，如果没有就查全部
        if (null != keyword && !"".equals(keyword)){
            //page = sysUserRepository.findByNameLikeOrPhoneLikeOrCnnameLike(keyword,keyword,keyword,pageable);
            //page = sysUserRepository.findByNameLike("%"+keyword+"%",pageable);
            page = sysUserRepository.findByNameLikeOrPhoneLikeOrCnnameLike(
                    "%"+keyword+"%"
                    ,"%"+keyword+"%"
                    ,"%"+keyword+"%"
                    ,pageable);

        }else{
            page = sysUserRepository.findAll(pageable);
        }
        //在没有新知识补充之前，看来只能用hashmap去构造返回的数据了。
        //先构造返回的数据结构
        return new ResponseData(ExceptionMsg.SUCCESS,page);
    }



    //create 前后端分离后，就暂时不用了。
    //store
    @ResponseBody
    @RequestMapping(value = "/create",method = RequestMethod.POST)
    public Response APIstore(@RequestBody Map<String ,Object> params){
        List<String > rolestrs;
        try {
            rolestrs =(ArrayList) params.get("roles");
        }catch (Exception e){
            return result(ExceptionMsg.FAILED);
        }
        List<SysRole> roles = new ArrayList<>();
        for (String rolestr : rolestrs){
            SysRole role = sysRoleRepository.findByRole(rolestr);
            roles.add(role);
        }
        SysUser sysUser = new SysUser();
        sysUser.setPhone(params.get("phone").toString());
        sysUser.setCnname(params.get("cnname").toString());
        sysUser.setName(params.get("name").toString());
        sysUser.setRoles(roles);
        sysUser.setEnabled((Boolean)params.get("enabled"));
        //还需要ip 啊，什么的，暂时就不弄了。
        sysUserRepository.save(sysUser);

        return new ResponseData(ExceptionMsg.SUCCESS,sysUser);
    }
    //show 前后端分离后，就暂时不用了
    //edit 前后端分离后，就暂时不用了
    //update id put
    @ResponseBody
    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    public Response APIupdate(@PathVariable("id")int id
            ,@RequestBody Map<String ,Object> params
//            ,@RequestParam(value = "cnname") String cnname
//            ,@RequestParam(value = "name") String name
//            ,@RequestParam(value = "phone") String phone
//            ,@RequestParam(value = "roles") ArrayList roles
//            ,@RequestParam(value = "enabled") Boolean enabled
    ){


        //List<Object> listRole = JSON.parseArray(params.get("roles").toString());
        List<String > rolestrs = new ArrayList<>();
        try{
            rolestrs = (ArrayList) params.get("roles");
        }catch (Exception e){
            return result(ExceptionMsg.FAILED);
        }
        List<SysRole> roles = new ArrayList<>();
        for (String rolestr : rolestrs){
            SysRole role = sysRoleRepository.findByRole(rolestr);
            roles.add(role);
        }
        //先验证需要参数的合法性，必须一次性都合法，否则返回错误，这个先忽略然后
        SysUser sysUser = sysUserRepository.findById(id);
        sysUser.setPhone(params.get("phone").toString());
        sysUser.setCnname(params.get("cnname").toString());
        sysUser.setName(params.get("name").toString());
        sysUser.setRoles(roles);
        sysUser.setEnabled((Boolean)params.get("enabled"));
        sysUserRepository.save(sysUser);


//        System.out.println("roles：" + params.get("roles") + params.get("roles").getClass()+"___"
//        +"enabled：" + params.get("enabled") + params.get("enabled").getClass());

        return new ResponseData(ExceptionMsg.SUCCESS,sysUser);
//        start = start < 0 ? 0 : start;
//        Sort sort = Sort.by(Sort.Direction.DESC, sortq);
//        Pageable pageable = PageRequest.of(start-1,limit,sort);
//        //得到了初始的数据
//        Page<SysUser> page = sysUserRepository.findAll(pageable);
//        //在没有新知识补充之前，看来只能用hashmap去构造返回的数据了。
//        //先构造返回的数据结构
//        return new ResponseData(ExceptionMsg.SUCCESS,page);
    }
    //destroy id delete
    @ResponseBody
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public Response APIdestroy(@PathVariable("id")int id){
        sysUserRepository.deleteById(id);
        return result(ExceptionMsg.SUCCESS);
    }


    //冻结用户
    @ResponseBody
    @RequestMapping(value = "/Freeze/{id}",method = RequestMethod.POST)
    public Response APIFreeze(@PathVariable("id")int id){
        //取出用户
        SysUser sysUser = sysUserRepository.findById(id);
        sysUser.setEnabled(false);
        sysUserRepository.save(sysUser);
        return result(ExceptionMsg.SUCCESS);
    }

    //重置密码
    @ResponseBody
    @RequestMapping(value = "/ResetPwd/{id}",method = RequestMethod.POST)
    public Response APIResetPwd(@PathVariable("id")int id
            ,@RequestBody Map<String ,Object> params
    ){
        //首先获取到 加密密码
        BCryptPasswordEncoder encoder =new BCryptPasswordEncoder();
        String encodePassword = encoder.encode(params.get("pwd").toString());
        //然后取到用户
        SysUser sysUser = sysUserRepository.findById(id);
        sysUser.setPassword(encodePassword);
        //然后保存
        sysUserRepository.save(sysUser);
        return result(ExceptionMsg.SUCCESS);
    }







}
